import 'dart:io';

import 'package:get/get.dart';

class OssService extends GetConnect {
  Future<Response> sign(String name) async {
    return get(
      'https://life-api.vertu.cn/mto/v2/console/api/admin/v1/ossSign?dir=$name',
    );
  }

  Future<String> upload(String dir, File file) async {
    final res = await sign(dir);
    if (res.body == null) {
      return '';
    }
    final data = res.body['data'];
    final formData = FormData({});
    Map<String, String> fieldsMap = {
      'key': data['dir'],
      'OSSAccessKeyId': data['accessid'],
      'policy': data['policy'],
      'signature': data['signature'],
      'expire': data['expire'].toString(),
    };
    String filename = file.path.split('/').last;
    formData.fields.addAll(fieldsMap.entries);
    formData.files.add(
      MapEntry('file', MultipartFile(file, filename: filename)),
    );
    String url = 'https://cdn-www.vertu.com';
    final result = await post(url, formData);
    if (result.isOk) {
      return '$url/${data['dir']}';
    }
    return '';
  }
}
